import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Order.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fsuper/fsuper.dart';

///商品订单

class MyOrderPage extends StatefulWidget {
  final String type;

  const MyOrderPage({Key key, this.type}) : super(key: key);

  @override
  _MyOrderPageState createState() => _MyOrderPageState();
}

class _MyOrderPageState extends State<MyOrderPage> {
  EasyRefreshController _controller = EasyRefreshController();
  var item = [];
  int pageNum = 0;

  @override
  void initState() {
    super.initState();
    getOrderList(true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Theme.of(context).cardColor,
        title: Text(
          widget.type == "01" ? "我买到的" : "我卖出的",
          style: TextStyle(fontSize: 18),
        ),
        elevation: 0.0,
      ),
      body: EasyRefresh.custom(
        enableControlFinishRefresh: true,
        header: CommWidget.commHeader(),
        footer: CommWidget.commFooter(),
        emptyWidget: item.length == 0 ? CommWidget.nullWidget() : null,
        controller: _controller,
        enableControlFinishLoad: true,
        slivers: <Widget>[
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                return _itemWidget(index);
              },
              childCount: item.length,
            ),
          )
        ],
        onRefresh: () => getOrderList(true),
        onLoad: () => getOrderList(false),
      ),
    );
  }

  ///item列表
  Widget _itemWidget(int index) {
    Order order = item[index];
    return Card(
      margin: EdgeInsets.only(left: 10, right: 10, top: 10),
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.all(
          Radius.circular(10.0),
        ),
      ),
      child: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          children: <Widget>[
            _topWidget(order),
            SizedBox(height: 6),
            _goodsWidget(order),
            _moneyWidget(order),
            Divider(),
            _bottomWidget(order),
          ],
        ),
      ),
    );
  }

  ///卡片头部
  Widget _topWidget(Order order) {
    String userName, userImg, status;
    if (widget.type == "01") {
      userName = order.sellerName;
      userImg = order.sellerImg;
      if (order.status == 0) {
        status = "等待付款";
      } else if (order.status == 1) {
        status = "等待发货";
      } else if (order.status == 2) {
        status = "卖家已发货";
      } else if (order.status == 3) {
        status = "交易成功";
      } else if (order.status == 4) {
        status = "退款中";
      } else if (order.status == 5) {
        status = "已退款";
      } else {
        status = "交易关闭";
      }
    } else {
      userName = order.buyerName;
      userImg = order.buyerImg;
      if (order.status == 0) {
        status = "等待付款";
      } else if (order.status == 1) {
        status = "等待发货";
      } else if (order.status == 2) {
        status = "等待对方确认";
      } else if (order.status == 3) {
        status = "交易成功";
        if (null != order.tradeGrade) {
          status = "买家已评价";
        }
      } else if (order.status == 4) {
        status = "退款中";
      } else if (order.status == 5) {
        status = "已退款";
      } else {
        status = "交易关闭";
      }
    }
    return FSuper(
      height: 28,
      text: userName,
      textAlignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 32),
      child1Alignment: Alignment.centerLeft,
      child2Alignment: Alignment.centerRight,
      child2: Text(
        status,
        style: TextStyle(
          fontSize: 14,
          color: Colors.deepOrange,
          fontWeight: FontWeight.w500,
        ),
      ),
      child1: ClipOval(
        child: CachedNetworkImage(
          height: 28,
          width: 28,
          fit: BoxFit.cover,
          imageUrl: Api.getUrl(userImg),
          errorWidget: (context, url, error) => Image.asset(
            Comm.IMG_DEFAULT,
            fit: BoxFit.contain,
          ),
        ),
      ),
    );
  }

  ///商品描述
  Widget _goodsWidget(Order order) {
    return FSuper(
      height: 64,
      text: order.goodsName,
      textWeight: FontWeight.w500,
      textAlign: TextAlign.start,
      textAlignment: Alignment.topLeft,
      padding: EdgeInsets.only(left: 70),
      child1Alignment: Alignment.centerLeft,
      child1: Container(
        width: 64,
        height: 64,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: CachedNetworkImage(
            imageUrl: Api.getUrl(order.goodsImg.split(",")[0]),
            errorWidget: (context, url, error) => CommWidget.imgError(),
            fit: BoxFit.fill,
          ),
        ),
      ),
      onClick: () {
        String url = "${Routers.PAGE_ORDERINFO}?orderId=${order.orderId}";
        Routers.router.navigateTo(
          context,
          url,
          transition: TransitionType.inFromRight,
        );
      },
    );
  }

  ///付款金额
  Widget _moneyWidget(Order order) {
    String hint;
    if (widget.type == "01") {
      hint = "实付款 ";
    } else {
      hint = "实收款 ";
    }
    String money = "¥${order.price * order.goodsNum}";
    return FSuper(
      text: money,
      textSize: 18,
      textColor: Colors.redAccent,
      textWeight: FontWeight.bold,
      textAlignment: Alignment.centerRight,
      child1: Text(hint, style: TextStyle(fontSize: 12)),
      child1Alignment: Alignment.centerRight,
      child1Margin: EdgeInsets.only(right: money.length * 10.0),
    );
  }

  ///底部
  Widget _bottomWidget(Order order) {
    String hint;
    if (order.status == 0) {
      hint = widget.type == "01" ? "去付款" : "关闭交易";
    } else if (order.status == 1) {
      hint = widget.type == "01" ? "提醒发货" : "发货";
    } else if (order.status == 2) {
      hint = widget.type == "01" ? "确认收货" : "提醒收货";
    } else if (order.status == 6) {
      hint = "删除订单";
    } else {
      hint = widget.type == "01" ? "评价" : "查看评价";
    }
    return FSuper(
      height: 32,
      text: widget.type == "01" ? "联系卖家" : "联系买家",
      textAlignment: Alignment.centerLeft,
      padding: EdgeInsets.only(left: 18),
      child1: Image.asset(Comm.IMG_CONTACT,
          width: 16, height: 16, fit: BoxFit.fill),
      child1Alignment: Alignment.centerLeft,
      child2Alignment: Alignment.centerRight,
      onChild2Click: () => showMsgDialog(context, order.orderId),
      child2: Offstage(
        offstage: order.status != 6,
        child: Container(
          height: 34,
          width: 84,
          child: Text(hint),
          alignment: Alignment.center,
          decoration: BoxDecoration(
            border: Border.all(color: Color(0xffcccccc), width: 1),
            borderRadius: BorderRadius.circular(20),
          ),
        ),
      ),
      onClick: () {
        User user = User(
          userId: widget.type == "01" ? order.sellerId : order.buyerId,
          userName: widget.type == "01" ? order.sellerName : order.buyerName,
          imgUrl: widget.type == "01" ? order.sellerImg : order.buyerImg,
        );
        var jsons = jsonEncode(Utf8Encoder().convert(json.encode(user)));
        String url = '${Routers.PAGE_CHAT}?user=$jsons&msgTag=${order.goodsId}';
        Routers.router
            .navigateTo(context, url, transition: TransitionType.inFromRight);
      },
    );
  }

  void showMsgDialog(BuildContext context, String orderId) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("您确定要删除该订单吗？", style: TextStyle(fontSize: 16)),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
              FlatButton(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  _delOrder(orderId);
                },
              ),
            ],
          );
        });
  }

  ///删除订单
  void _delOrder(String orderId) {
    CancelFunc delLoading = Toast.loading("删除中...");
    String url = "${Api.URL_ORDER_DEL}?orderId=$orderId";
    Http.get(url, successCallBack: (data) {
      delLoading();
      getOrderList(true);
    }, errorCallBack: (error) {
      Toast.show(error);
      delLoading();
    });
  }

  ///获取订单列表
  Future getOrderList(bool isRefresh) async {
    Map<String, String> params = Map();
    params["type"] = widget.type;
    params["pageNum"] = '${isRefresh ? 0 : pageNum}';
    Http.get(Api.URL_ORDER_LIST, params: params, successCallBack: (data) {
      List list = json.decode(data).map((m) => Order.fromJson(m)).toList();
      if (isRefresh) {
        _controller.finishRefresh();
        item.clear();
        pageNum = 0;
      } else {
        _controller.finishLoad(noMore: null != list && list.length < 10);
      }
      setState(() {
        item.addAll(list);
        pageNum++;
      });
    }, errorCallBack: (msg) {
      _controller.finishRefresh();
      _controller.finishLoad();
    });
  }
}
